import React, {useEffect} from 'react';
import {Avatar, Card, CardContent, CardHeader} from "@material-ui/core";
import {color, toFirstLetter} from "../../../../../../assets/functions/functions";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import Divider from "@material-ui/core/Divider";
import {makeStyles} from "@material-ui/styles";

const useStyles = makeStyles(theme => ({
  cardHeight: {
    height: "100%",
    // margin: theme.spacing(2, 2, 2, 2),
    // padding: theme.spacing(2),
    // borderRadius: theme.spacing(2)
  },
}))

export default function VisualizationPreview(props) {
  const {
    classes,
    vizData: {
      indicator: {
        indicatorType,
        name
      },
      displayCode,
      scriptData
    }
  } = props;
  const styles = useStyles();

  useEffect(() => {
    const script = document.createElement("script");
    script.innerHTML = scriptData;
    document.getElementById("root").appendChild(script);
    return () => {
      document.getElementById("root").removeChild(script);
    };
  }, [scriptData]);

  return (
    <>
      <Card className={styles.cardHeight} elevation={5}>
        <CardHeader
          style={{height: "20%"}}
          avatar={<Avatar style={{backgroundColor: color(indicatorType), color: "#fff"}}>
            {toFirstLetter(indicatorType)}
          </Avatar>}
          title={
            <Grid container alignItems="center" >
              <Grid item xs>
                <Grid container direction="column">
                  <Typography variant="h6">{name}</Typography>
                  <Typography variant="overline">{indicatorType}</Typography>
                </Grid>
              </Grid>
            </Grid>
          }
        />
        <Divider className={classes.divider}/>
        <CardContent style={{backgroundColor: '#fff'}}>
          <Grid container direction="column" justify="center" alignItems="center" style={{color: '#000'}}>
            <Grid item>
              {displayCode}
            </Grid>
          </Grid>
        </CardContent>
      </Card>
    </>
  );
}
